﻿using Station.Inspect;
using Station.Inspect.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using thinger.VisitionDAL;
using Vision.Common;

namespace Station.Common.Rejudgment
{
	/// <summary>
	/// 检测&复判信息列表
	/// </summary>
	public class ErrList
	{
		public string FaceName { get; set; }
		protected List<NodeMark> Marks;

		public bool IsBaofei { set; get; }

		//运动镜头
		public List<ErrCamera> ErrCameras { get; set; } = new List<ErrCamera>();

		//待复判有cell元件
		public List<ErrComponent> ErrComponents { get; set; } = new List<ErrComponent>();

		//待复判无cell元件
		public List<ErrComponent> ErrLibComponents { get; set; } = new List<ErrComponent>();

		/// <summary>
		/// 二维码数据列表
		/// </summary>
		public List<ErrComponent> MatrixComponents { get; set; } = new List<ErrComponent>();

		public ErrList(string faceName, List<NodeComponent> compnts, List<NodeMark> marks)
		{
			var pts = new PointF[1];
			FaceName = faceName;
			Marks = marks;
			IsBaofei = false;
			foreach (var comp in compnts)
			{
				foreach (var ele in comp.Elements)
				{
					//var camera = new ErrCamera();
					var errComp = new ErrComponent();
					errComp.Position = ele.Rect;
					errComp.Angle = ele.Angle;
					errComp.Lib = ele.Lib;
					errComp.MarkID = comp.ID;
					var startPos = StaInspect.Instance.Rbt.P2TPByOrig(ele.StartPoint);
					var size = StaInspect.Instance.Rbt.Point2TP(new PointF(ele.Size.Width, ele.Size.Height));
					errComp.RealPosition = new RectangleF((float)startPos.x, (float)startPos.y, -(float)size.x, -(float)size.y);

					if (ele.Lib != null)
					{
						Matrix matrix = new Matrix();
						matrix.Translate(ele.StartPoint.X, ele.StartPoint.Y);
						matrix.Rotate(ele.Angle);
						foreach (var cell in ele.Lib.NodeCells)
						{
							pts[0] = new PointF(cell.StartPoint.X + cell.Size.Width / 2, cell.StartPoint.Y + cell.Size.Height / 2);
							matrix.TransformPoints(pts);

							var errCell = new ErrCell();
							errCell.ID = comp.ID + cell.ID;
							errCell.Rect = cell.Rect;
							errCell.Pos = pts[0];
							errCell.RealPos = StaInspect.Instance.Rbt.P2TPByOrig(errCell.Pos).ToPointF();
							errComp.ErrCells.Add(errCell);
						}
					}

					if (ele.Lib == null || (!ele.Lib.IsMatrixPos && !ele.Lib.IsLablePos && !ele.Lib.IsBadMarkPos))
						AddToCamera(errComp);
					else
						MatrixComponents.Add(errComp);
				}
			}
		}

		public void AddToCamera(ErrComponent ele)
		{
			//var r = ele.GetRect();
			//var nR = new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
			foreach (var camera in ErrCameras)
			{
				if (camera.TryAdd(ele))
				{
					return;
				}
			}
			var ca = new ErrCamera();
			ca.TryAdd(ele);
			ErrCameras.Add(ca);
			//ErrCamera camera = ErrCameras.Find(p => p.FovRect.Contains(nR));
			//if(camera == null)
			//{
			//    camera = new ErrCamera();
			//    ErrCameras.Add(camera);
			//}
			//camera.Add(ele);
		}

		public string FileName { get; set; }

		public void SetNG()
		{
			IsBaofei = false;
			foreach (var comp in ErrComponents)
			{
				foreach (var cell in comp.ErrCells)
				{
					if (cell.Status == CellStatus.OK)
					{
						cell.Status = CellStatus.NG;
						Console.WriteLine(cell.ID + " ng---------------");
					}
				}
			}

			foreach (var comp in ErrLibComponents)
			{
				if (comp.Status == CellStatus.OK)
				{
					comp.Status = CellStatus.NG;
					IsBaofei = true;
				}
			}
		}

		public List<cell_info> mapInfos = new List<cell_info>();

		public void Save(string code)
		{
			FileName = code;
			Font font = new Font("微软雅黑", 20);
			string basePath = StaInspect.Instance.loadPath + "\\Savemap";

			if (!string.IsNullOrEmpty(StaInspect.Instance.pici))
			{
				basePath += $"\\{StaInspect.Instance.pici}";
			}
			if (string.IsNullOrEmpty(FileName))
				FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss");
			string path = basePath + "\\板号-" + FileName + "\\" + FaceName;
			string markPath = path + "\\Mark";
			string passPath = path + "\\PASS";
			string okPath = path + "\\OK";
			string ngPath = path + "\\NG";
			Directory.CreateDirectory(markPath);
			Directory.CreateDirectory(passPath);
			Directory.CreateDirectory(okPath);
			Directory.CreateDirectory(ngPath);
			foreach (var mark in Marks)
			{
				string srcImage = $"\\SrcImage{mark.ID}.png";
				mark.SrcImage?.Save(markPath + srcImage);
				string dstImg = $"\\DstImage{mark.ID}.png";
				mark.DstImage?.Save(markPath + dstImg);
			}
			mapInfos.Clear();
			foreach (var camera in ErrCameras)
			{
				foreach (ErrComponent comp in camera.ErrComponents)
				{
					cell_info mapInfo = new cell_info();
					string fileName = $"\\PCS-{comp.MarkID}-Lib-{comp.Lib?.ID}";
					var status = comp.GetState();
					mapInfo.cellid = comp.MarkID;
					mapInfo.facename = FaceName;
					comp.facename = FaceName;
					if (status == CellStatus.PASS)
					{
						fileName = passPath + fileName;
						mapInfo.state = 1;
					}
					else if (status == CellStatus.OK)
					{
						fileName = okPath + fileName;
						mapInfo.state = 1;
					}
					else
					{
						fileName = ngPath + fileName;
						mapInfo.state = 0;

						//if (comp.RectErrs?.Count > 0)
						//{
						//	// 获取报点列表
						//	var errs = comp.RectErrs?.Select(s => s.Name).Distinct().ToList();

						//	if (errs?.Count > 0)
						//	{
						//		mapInfo.rectErrs = string.Join(",", errs);
						//	}

						//	File.AppendAllText(fileName + ".txt", $"追加errs数量：{errs?.Count}");

						//}

						if (comp.ErrCells?.Count > 0)
						{
							List<string> strList = new List<string>();

							var errrList = comp.ErrCells.Where(w => w.ID == mapInfo.cellid);

							foreach (var errr in errrList)
							{
								strList.AddRange(errr.RectErrs?.Select(s => s.Name).Distinct().ToList());
							}

							var errrRect = strList.Select(s => s).Distinct().ToList();

							// 获取报点列表

							if (errrRect?.Count > 0)
							{
								mapInfo.rectErrs = string.Join(",", errrRect);
							}

							File.AppendAllText(fileName + ".txt", $"追加errs数量：{errrRect?.Count}");
						}

						// 获取cell里面的异常列表

						File.AppendAllText(fileName + ".txt", $"追加测试异常：{mapInfo.rectErrs}");
					}
					SaveErrInfo(fileName + ".txt", comp);

					if (comp.Image != null)
					{
						comp.Image.Save(fileName + ".png", ImageFormat.Png);
						mapInfo.img = fileName + ".png";
						Graphics g = Graphics.FromImage(comp.Image);
						foreach (var item in comp.ErrCells)
						{
							Pen borderPen = item.Status == CellStatus.NG ? Pens.Red : Pens.LightGreen;

							int cx = (item.Rect.Left + item.Rect.Right) / 2;
							int cy = (item.Rect.Top + item.Rect.Bottom) / 2;
							g.DrawRectangle(borderPen, item.Rect);
							g.DrawLine(Pens.Black, cx - 20, cy, cx + 20, cy);
							g.DrawLine(Pens.Black, cx, cy - 20, cx, cy + 20);
							g.DrawString($"{item.ID}", font, Brushes.Black, cx + 10, cy + 10);
							if (item.Status.ToString() == "NG")
							{
								g.DrawString($"状态:{item.Status}", font, Brushes.Red, cx - 10, cy - 80);
							}
							else
							{
								g.DrawString($"状态:{item.Status}", font, Brushes.Green, cx - 10, cy - 80);
							}

							foreach (var orr in item.RectErrs)
							{
								g.DrawRectangle(Pens.Red, orr.rect);
								if (string.IsNullOrEmpty(orr.Name) == false)
								{
									g.DrawString(orr.Name, font, Brushes.Red, orr.rect.Right + 10, orr.rect.Bottom - 10);
								}
							}
						}
						comp.Image.Save(fileName + "-Cell.png", ImageFormat.Png);
						mapInfo.imgcenter = fileName + "-Cell.png";
						if (StaInspect.Instance.isMakeBigImg)
							if (FaceName == "A")
							{
								StaInspect.Instance.gA.DrawImage(comp.Image, comp.Position.Left, comp.Position.Top, comp.Position.Width, comp.Position.Height);
							}
							else if (FaceName == "B")
							{
								StaInspect.Instance.gB.DrawImage(comp.Image, comp.Position.Left, comp.Position.Top, comp.Position.Width, comp.Position.Height);
							}
					}
					mapInfos.Add(mapInfo);
				}
			}
		}

		/*
       * cellID，类型，属性
       * 类型：
       * 1=中心点坐标
       * 2=框属性
       * 11=矩形，得分,
       *
      */

		private void SaveErrInfo(string fileName, ErrComponent comp)
		{
			try
			{
				var centerPt = comp.CenterPoint;
				string str = $"-1,1,{(comp.Position.Left + comp.Position.Right) / 2}.{(comp.Position.Top + comp.Position.Bottom) / 2},{centerPt.X},{centerPt.Y}\r\n";
				foreach (var item in comp.RectErrs)
				{
					str += $"-1,11,{item.Score},{item.Name},{item.rect.Left},{item.rect.Top},{item.rect.Width},{item.rect.Height}\r\n";
				}
				foreach (var cell in comp.ErrCells)
				{
					int x = (cell.Rect.Left + cell.Rect.Right) / 2;
					int y = (cell.Rect.Top + cell.Rect.Bottom) / 2;
					str += $"{cell.ID},1,{x},{y},{cell.RealPos.X},{cell.RealPos.Y}\r\n";
					str += $"{cell.ID},2,{cell.Rect.Left},{cell.Rect.Top},{cell.Rect.Width},{cell.Rect.Height},0\r\n";
					foreach (var item in cell.RectErrs)
					{
						str += $"{cell.ID},11,{item.Score},{item.Name},{item.rect.Left},{item.rect.Top},{item.rect.Width},{item.rect.Height}\r\n";
					}
				}
				File.AppendAllText(fileName, str);
			}
			catch (Exception ex)
			{
			}
		}
	}
}